package leetcode.code0146;


//执行用时：32 ms, 在所有 Java 提交中击败了99.97%的用户
//
//内存消耗：106 MB, 在所有 Java 提交中击败了98.89%的用户
//
//通过测试用例：22 / 22
public class LRUCache {

	int capacity;
	int size;
//	Map<Integer, Node> hash;
	Node[] hash;
	Node head;
	Node tail;

	public LRUCache(int capacity) {
		this.capacity = capacity;
//		this.hash = new HashMap<>();
		this.hash = new Node[10001];
		this.head = new Node();
		this.tail = new Node();
		this.head.next = this.tail;
		this.tail.last = this.head;
		this.size = 0;
	}

	public int get(int key) {
		int ans = 0;
		Node cur = hash[key];
		if (cur != null) {
			ans = cur.value;
			this.updateNode(key);
		} else {
			ans = -1;
		}
//		System.out.println(ans);
		return ans;
	}

	public void put(int key, int value) {
		if (hash[key] == null) {
			Node cur = new Node(key, value);
			hash[key] = cur;
			this.add2tail(cur);
			if (this.size < this.capacity) {
				this.size++;
			} else {
				this.removeFirst();
			}
		} else {
			this.updateNode(key, value);
		}
	}

	private void updateNode(int key) {
		Node cur = hash[key];
		cur.last.next = cur.next;
		cur.next.last = cur.last;
		this.add2tail(cur);
	}

	private void updateNode(int key, int value) {
		Node cur = hash[key];
		cur.value = value;
		cur.last.next = cur.next;
		cur.next.last = cur.last;
		this.add2tail(cur);
	}

	private void add2tail(Node node) {
		Node tmp = tail.last;
		tmp.next = node;
		node.last = tmp;
		tail.last = node;
		node.next = tail;
	}

	private void removeFirst() {
		Node old = head.next;
		old.next.last = head;
		head.next = old.next;
		hash[old.key] = null;
	}

	class Node {
		int key;
		int value;
		Node next;
		Node last;

		public Node() {

		}

		public Node(int key, int value) {
			this.key = key;
			this.value = value;
		}
	}

	public static void main(String[] args) {
		LRUCache lRUCache = new LRUCache(2);
		lRUCache.put(1, 1); // 缓存是 {1=1}
		lRUCache.put(2, 2); // 缓存是 {1=1, 2=2}
		lRUCache.get(1); // 返回 1
		lRUCache.put(3, 3); // 该操作会使得关键字 2 作废，缓存是 {1=1, 3=3}
		lRUCache.get(2); // 返回 -1 (未找到)
		lRUCache.put(4, 4); // 该操作会使得关键字 1 作废，缓存是 {4=4, 3=3}
		lRUCache.get(1); // 返回 -1 (未找到)
		lRUCache.get(3); // 返回 3
		lRUCache.get(4); // 返回 4
	}

}
